/**
 * 账号设置
 * */
import React, { useState } from 'react';
import { Modal, Input, Form, Select, message, Spin } from 'antd';
import { connect } from 'umi';
import { isArray } from 'lodash';
import { useRequest, defaultFormatResult } from '@/hooks';
import { getEmployeeInfoList } from '@/services/components/userform';
import { getEmailList, saveAddAccount, saveEditAccount } from '../../service';

const { Option } = Select;

const formItemLayout = {
    labelCol: {
        sm: { span: 7 }
    },
    wrapperCol: {
        sm: { span: 16 }
    }
};

const AccountModal = ({ form, user, channelCode, children, data, onSuccess }) => {
    const { getFieldDecorator, validateFields } = form;
    const { firstOrgInfo = {}, employeeCode } = user;
    const { firstCompanyCode } = firstOrgInfo;
    const [visible, setVisible] = useState(false);
    const employeeRef = React.useRef(null);
    const firstRef = React.useRef(true);

    // 搜索人员
    const {
        data: employeeList,
        loading: employeeLoading,
        run: fetchEmployeeList,
        mutate: setEmployeeList
    } = useRequest(
        tagName =>
            getEmployeeInfoList({
                // administrativeOrganizationCode: firstCompanyCode,
                name: tagName
            }),
        {
            debounceInterval: 500,
            manual: true,
            initialData: [],
            formatResult: res => {
                if (res) {
                    firstRef.current = false;
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        if (!employeeRef.current) {
                            employeeRef.current = resData;
                        }
                        return resData;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    // 获取邮箱列表
    const { data: emailList, run: fetchEmailList } = useRequest(
        () => getEmailList({ organizationCode: firstCompanyCode }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 新增渠道账号保存
    const { loading: addModelLoading, run: handleOnAddSave } = useRequest(
        value => saveAddAccount({ ...value, channelCode, authType: 2 }),
        {
            manual: true,
            onSuccess: result => {
                const { code, msg } = result;
                if (code === 10000) {
                    message.success('操作成功');
                    if (onSuccess) {
                        onSuccess(2);
                    }
                    setVisible(false);
                } else {
                    message.error(msg);
                }
            }
        }
    );

    // 编辑渠道账号保存
    const { loading: editModelLoading, run: handleOnEditSave } = useRequest(
        value => saveEditAccount({ ...value, accountId: data?.id, authType: 2 }),
        {
            manual: true,
            onSuccess: result => {
                const { code, msg } = result;
                if (code === 10000) {
                    message.success('操作成功');
                    if (onSuccess) {
                        onSuccess(2);
                    }
                    setVisible(false);
                } else {
                    message.error(msg);
                }
            }
        }
    );

    // 确定
    const handleOk = () => {
        validateFields((err, values) => {
            if (!err) {
                const { accountReceiveMailList = [] } = values;
                const params = {
                    ...values,
                    accountReceiveMailList: isArray(accountReceiveMailList)
                        ? accountReceiveMailList
                        : [accountReceiveMailList]
                };
                if (data) {
                    handleOnEditSave(params);
                    return;
                }
                handleOnAddSave(params);
            }
        });
    };

    // 取消
    const handleCancel = () => {
        setVisible(false);
    };

    // 显示modal
    const handleModal = () => {
        setVisible(true);
        if (!emailList || emailList.length === 0) {
            fetchEmailList();
        }
    };

    const handleEmployeeFocus = () => {
        if (employeeRef.current) {
            setEmployeeList(employeeRef.current);
        }
    };

    const handleSearch = _value => {
        if (_value) {
            fetchEmployeeList(_value.trim());
        }
    };

    React.useEffect(() => {
        if (visible && employeeList?.length === 0) {
            fetchEmployeeList();
        }
        if (!visible) {
            form.resetFields();
        }
    }, [visible]);

    return (
        <>
            <div onClick={handleModal}>{children}</div>
            <Modal
                title={data ? '编辑渠道账号' : '新增渠道账号'}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                width={640}
                confirmLoading={addModelLoading || editModelLoading}
            >
                <Form {...formItemLayout} labelAlign="right" style={{ paddingTop: '30px' }}>
                    <Form.Item label="账号">
                        {getFieldDecorator('channelAccount', {
                            initialValue: data?.channelAccount || '',
                            rules: [{ required: true, message: '请输入账号' }]
                        })(<Input placeholder="请输入账号" type="text" maxLength={50} />)}
                    </Form.Item>
                    <Form.Item label="密码">
                        {getFieldDecorator('channelPassword', {
                            initialValue: data?.channelPassword || '',
                            rules: [{ required: true, message: '请输入密码' }]
                        })(<Input.Password placeholder="请输入密码" maxLength={50} />)}
                    </Form.Item>
                    <Form.Item label="姓名">
                        {getFieldDecorator('accountName', {
                            initialValue: data?.accountName || '',
                            rules: [{ message: '请输入姓名' }]
                        })(<Input placeholder="请输入姓名" maxLength={20} />)}
                    </Form.Item>
                    <Form.Item label="授权用户">
                        <Spin spinning={firstRef.current && employeeLoading}>
                            {getFieldDecorator('authEmployeeCodes', {
                                initialValue: data ? data?.authEmployeeCodes : [employeeCode],
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择授权用户'
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    placeholder="请选择授权用户"
                                    allowClear
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    onFocus={handleEmployeeFocus}
                                    onSearch={handleSearch}
                                    filterOption={false}
                                >
                                    {employeeList?.map(item => (
                                        <Option value={item.employeeCode} key={item.employeeCode}>
                                            {item.employeeName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    {channelCode !== 'bosszp' && (
                        <Form.Item label="接收简历邮箱">
                            {getFieldDecorator('accountReceiveMailList', {
                                initialValue:
                                    channelCode === 'xmrc'
                                        ? data?.accountReceiveMails
                                        : data?.accountReceiveMails?.split(',') || undefined,
                                rules: [{ required: true, message: '请选择接收简历邮箱' }]
                            })(
                                <Select
                                    mode={channelCode === 'xmrc' ? '' : 'multiple'}
                                    placeholder="请选择接收简历邮箱"
                                >
                                    {emailList?.map(i => (
                                        <Option key={i.id} value={i.email}>
                                            {i.email}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                    )}
                </Form>
            </Modal>
        </>
    );
};
export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(AccountModal));
